//
//  UserViewController.m
//  Snigger
//
//  Created by Young on 16/8/16.
//  Copyright © 2016年 Smile. All rights reserved.
//

#import "UserViewController.h"

#import "UIView+Supplement.h"
#import "DrawerManager.h"
#import "StretchingManager.h"
#import "LeftView.h"
#import "LoginViewController.h"
#import "DownloadViewController.h"

#define kHeaderImageViewHight 210
#define kScreenWidth [UIScreen mainScreen].bounds.size.width
#define kScreenHeight [UIScreen mainScreen].bounds.size.height
#define kButtonColor [UIColor colorWithRed:0 / 256.0 green:189 / 256.0 blue:237 / 256.0 alpha:1.0]

@interface UserViewController () <UITableViewDataSource, UITableViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIGestureRecognizerDelegate>

@property (weak, nonatomic) UIImageView *portrait;
@property (strong, nonatomic) UITableView *tableView;
@property (strong, nonatomic) NSArray *dataArray;
@property (strong, nonatomic) UIImageView *headerImageView;
@property (strong, nonatomic) StretchingManager *stretchingManager;

@end

@implementation UserViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"个人中心";
    self.automaticallyAdjustsScrollViewInsets = NO;
    // 初始化数组
    _dataArray = @[@"我的动态", @"我的下载", @"我的评论", @"清除缓存", @"我的收藏", @"我的消息", @"我的钱包"];
    // 初始化头像
    [self initPortrait];
    // 添加点按手势
    [self addTap];
    // 初始化tableView
    [self initTableView];
    // 头部视图拉伸效果的实现
    [self stretchHeaderView];
    // 添加登录按钮
    [self addUIBarButtonItem];

}

#pragma mark - 添加导航栏按钮
- (void)addUIBarButtonItem {
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Login" style:(UIBarButtonItemStylePlain) target:self action:@selector(loginClicked:)];
}

- (void)loginClicked:(UIBarButtonItem *)sender {
    LoginViewController *loginVC = [[LoginViewController alloc] init];
    [self.navigationController pushViewController:loginVC animated:YES];
}

#pragma mark - 头部视图拉伸效果的实现
- (void)stretchHeaderView {
    _headerImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kHeaderImageViewHight)];
    _headerImageView.contentMode = UIViewContentModeScaleToFill;
    _headerImageView.clipsToBounds = YES;
    _headerImageView.image = [UIImage imageNamed:@"headerImage"];
    
    _stretchingManager = [[StretchingManager alloc] init];
    [_stretchingManager stretchHeaderForTableView:_tableView withView:_headerImageView subViews:nil];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [_stretchingManager scrollViewDidScroll:scrollView];
}

- (void)viewDidLayoutSubviews
{
    [_stretchingManager resizeView];
}

#pragma mark - 初始化tableView
- (void)initTableView {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, kScreenWidth, [UIScreen mainScreen].bounds.size.height) style:(UITableViewStylePlain)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.tableView];
}

#pragma mark - 初始化头像视图
- (void)initPortrait {
    UIImageView *portrait = [[UIImageView alloc] initWithFrame:CGRectMake(10, 0, 39, 39)];
    portrait.layer.cornerRadius = portrait.bounds.size.width / 2.0;
    portrait.layer.masksToBounds = YES;
    portrait.image = [UIImage imageNamed:@"defaultUserIcon"];
    portrait.userInteractionEnabled = YES;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:portrait];
    _portrait = portrait;
}

#pragma mark - 添加点按手势方法
- (void)addTap {
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    UITapGestureRecognizer *portraitTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(portraitTapAction:)];
    tap.delegate = self;
    [self.view addGestureRecognizer:tap];
    [_portrait addGestureRecognizer:portraitTap];
    portraitTap.delegate = self;
    [self.navigationController.navigationBar addGestureRecognizer:tap];
}

- (void)tapAction:(UITapGestureRecognizer *)tap {
    [DrawerManager sharedDrawerManager].centerViewController.view.transform = CGAffineTransformIdentity;
    [[UIApplication sharedApplication].delegate window].subviews.firstObject.tx = [DrawerManager sharedDrawerManager].centerViewController.view.tx / 3.0;
}

#pragma mark - 获取系统相册
- (void)portraitTapAction:(UITapGestureRecognizer *)tap {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"SelectPicture" message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
    UIAlertAction *action_Camera = [UIAlertAction actionWithTitle:@"FromCamera" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        if ([UIImagePickerController isSourceTypeAvailable:(UIImagePickerControllerSourceTypeCamera)]) {
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.delegate = self;
            picker.editing = YES;
            picker.allowsEditing = YES;
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:picker animated:YES completion:nil];
        } else {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Camera failed to be obtained." message:nil preferredStyle:(UIAlertControllerStyleAlert)];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"Cancel" style:(UIAlertActionStyleCancel) handler:nil];
            [alert addAction:action];
            [self presentViewController:alert animated:YES completion:nil];
        }
    }];
    
    UIAlertAction *action_PhotoLibrary = [UIAlertAction actionWithTitle:@"FromPhotoLibrary" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            UIImagePickerController  *picker =[[UIImagePickerController alloc]init];
            picker.delegate = self;
            picker.editing = YES;
            picker.allowsEditing = YES;
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [self presentViewController:picker animated:YES completion:nil];
        } else {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"PhotoLibrary failed to be obtained." message:nil preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil];
            [alert addAction:action];
            [self presentViewController:alert animated:YES completion:nil];
        }
    }];
    UIAlertAction *action_Cancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
 
    }];
    [alert addAction:action_Camera];
    [alert addAction:action_PhotoLibrary];
    [alert addAction:action_Cancel];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    /**
     *  相机代理
     */
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
        
        // 获取裁剪图片
        UIImage *cameraImage = [info objectForKey:UIImagePickerControllerEditedImage];
        // 如果实拍的照,需要保存到本地
        UIImageWriteToSavedPhotosAlbum(cameraImage, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    }
    /**
     *  相册代理
     */
    else if (picker.sourceType == UIImagePickerControllerSourceTypePhotoLibrary) {
        // 获取裁剪的图片
        UIImage *photoLibraryImage = [info objectForKey:UIImagePickerControllerEditedImage];
        _portrait.image = photoLibraryImage;
        // 将图片转化成数据类型
//        NSData *data = UIImageJPEGRepresentation(photoLibraryImage, 0.00001);
//        AVFile *file = [AVFile fileWithName:@"userimage.png" data:data];
//        [file saveInBackground];
//        //
//        AVQuery *query = [AVQuery queryWithClassName:@"_User"];
//        [query whereKey:@"username" equalTo:[AVUser currentUser].username];
//        [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
//            if (!error) {
//                // 检索成功
//                AVObject *post = [AVObject objectWithoutDataWithClassName:@"_User" objectId:[[objects lastObject]objectId]];
//                [post setObject:file forKey:@"pictrue"];
//                [post saveInBackground];
//            }else {
//                NSLog(@"%@,%@",error,[error userInfo]);
//            }
//            
//        }];
    }
//    [self.tableView reloadData];
    [picker dismissViewControllerAnimated:YES completion:nil];
    
}

//保存照片成功后的回调
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error
  contextInfo:(void *)contextInfo{
//    NSString *msg = nil ;
//    if(error != NULL){
//        msg = @"保存图片失败" ;
//    }else{
//        msg = @"保存图片成功" ;
//        self.userHeadImage.image = image;
//        NSData *data = UIImageJPEGRepresentation(image, 0.00001);
//        AVFile *file = [AVFile fileWithName:@"userimage.png" data:data];
//        [file saveInBackground];
//        [self.tableView reloadData];
//        //更新属性
//        AVQuery *query = [AVQuery queryWithClassName:@"_User"];
//        [query whereKey:@"username" equalTo:[AVUser currentUser].username];
//        [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
//            if (!error) {
//                // 检索成功
//                AVObject *post = [AVObject objectWithoutDataWithClassName:@"_User" objectId:[[objects lastObject]objectId]];
//                [post setObject:file forKey:@"pictrue"];
//                [post saveInBackground];
//                [self.tableView reloadData];
//            } else {
//                // 输出错误信息
//                NSLog(@"Error: %@ %@", error, [error userInfo]);
//            }
//        }];
//        
//    }
//    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"保存图片结果提示"
//                                                    message:msg
//                                                   delegate:self
//                                          cancelButtonTitle:@"确定"
//                                          otherButtonTitles:nil];
//    
//    [alert show];
//    
}

#pragma mark - UITableViewDataSource / UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *const USER_CELL_IDENTIFIER = @"UserViewController";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:USER_CELL_IDENTIFIER];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:USER_CELL_IDENTIFIER];
    }
    cell.textLabel.text = _dataArray[indexPath.row];
    return cell;
}

#pragma mark - 解决手势冲突
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {//判断如果点击的是tableView的cell，就把手势给关闭了
        return NO;//关闭手势
    }//否则手势存在
    return YES;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    switch (indexPath.row) {
        case 0:
        {
            
        }
            break;
        case 1:
        {
            DownloadViewController *downloadVC = [[DownloadViewController alloc]init];
            [self.navigationController pushViewController:downloadVC animated:YES];
        }
            break;
        case 2:
        {
            
        }
            break;
        case 3:
        {
            
        }
            break;
        case 4:
        {
            
        }
            break;
        case 5:
        {
            
        }
            break;
            
        default:
            break;
    }
}









@end
